package org.ihelpuoo.db.sql;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.Map;

import org.ihelpuoo.io.CharInputStream;
import org.ihelpuoo.lang.InitializeException;
import org.ihelpuoo.lang.LoaderException;
import org.ihelpuoo.lang.StringUtils;

public class SQLSet
{
	public SQLSet()
	{
		sqls = new HashMap<String, SQLSegment>();
	}

	private Map<String, SQLSegment>	sqls;

	public void clear()
	{
		sqls.clear();
	}

	protected void loadByInputStream(InputStream ins) throws LoaderException, InitializeException
	{
		BufferedReader br = new BufferedReader(new InputStreamReader(ins));
		String line;
		StringBuffer sb = new StringBuffer();
		String name = null;
		try
		{
			while ((line = br.readLine()) != null)
			{
				if (line.startsWith("#"))
					continue;
				if (line.trim().length() == 0)
					continue;
				if (line.startsWith(":"))
				{
					addSqlSegment(sb,name);
					name = line.substring(1);
					sb = new StringBuffer();
				}
				else
				{
					if (line.trim().length() > 0 && null != name)
					{
						sb.append(line + "\n");
					}
				}
			}
			addSqlSegment(sb,name);

		}
		catch (IOException e)
		{
			throw new InitializeException(e.getMessage(),e);
		}
	}

	private void addSqlSegment(StringBuffer sb, String name) throws LoaderException
	{
		String s = StringUtils.trim(sb.toString());
		if (null != name && name.length() > 0 && s.length() > 0)
		{
			sqls.put(name,new SQLSegment(new CharInputStream(s)));
		}
	}

	public void load(String fileName) throws InitializeException
	{
		try
		{
			loadByInputStream(this.getClass().getClassLoader().getResourceAsStream(fileName));
		}
		catch (Exception e)
		{
			throw new InitializeException("expect \"" + fileName + "\" in classpath:\n"
					+ System.getProperty("sun.boot.class.path") + "!\n" + e.getMessage(),e);
		}
	}

	public SQLSegment get(String key) throws SQLNotFoundException
	{
		SQLSegment ss = (SQLSegment)sqls.get(key);
		if (null == ss)
			throw new SQLNotFoundException("Can not find SQL by key \"" + key + "\"");
		return (SQLSegment)ss.duplicate();
	}
}
